package com.norma.netty.study.netty.disruptor.core;

import com.lmax.disruptor.RingBuffer;
import com.norma.netty.study.netty.disruptor.TransData;
import com.norma.netty.study.netty.disruptor.TransDataWrapper;
import io.netty.channel.ChannelHandlerContext;
import lombok.Data;

/**
 * @author zhangchaofeng
 * @date 2021/1/5
 * @description
 */
@Data
public class MessageProducer {

    private RingBuffer<TransDataWrapper> ringBuffer;

    private String producerId;

    public MessageProducer(String producerId, RingBuffer<TransDataWrapper> ringBuffer) {
        this.ringBuffer = ringBuffer;
        this.producerId = producerId;
    }

    /**publish msg */
    public void sendData(ChannelHandlerContext ctx, TransData data) {
        long sequence = ringBuffer.next();
        try {
            TransDataWrapper transDataWrapper = ringBuffer.get(sequence);
            transDataWrapper.setCtx(ctx);
            transDataWrapper.setData(data);
        } finally {
            ringBuffer.publish(sequence);
        }
    }
}
